package com.qingcloud.base.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Cookie工具类
 */
public class CookieUtil {

//    //权限平台用户cookie
//    public static final String ADMIN_USER_ID_KEY = "adminUserId";
//
//    //权限平台用户cookie
//    public static final String ADMIN_USER_NAME_KEY = "adminUserName";
//
//    //权限平台用户cookie
//    public static final String ADMIN_USER_FULL_NAME = "adminFullName";
//
//    //权限平台用户cookie
//    public static final String ADMIN_TOKEN_KEY = "admin_token";

    private static final String ADMIN_USER_ID = "4028f481585db7d701585dc9f8a00018";

    public static final String USER_ID_KEY = "df_user_id";

    public static final String USER_NAME_KEY = "df_user_name";

    public static final String PROJECT_KEY = "df_project_id";

    public static final String ORG_KEY = "df_org_id";

    public static final String TOKEN_KEY = "df_token";

    private CookieUtil() {
    }

    /**
     * 添加cookie
     *
     * @param response
     * @param name     名称
     * @param value    值
     * @param maxAge   小于或等于0 不设置
     */
    public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        if (maxAge > 0) {
            cookie.setMaxAge(maxAge);
        }
        response.addCookie(cookie);
    }

    /**
     * 删除cookie
     */
    public static void removeCookie(HttpServletResponse response, String name) {
        Cookie uid = new Cookie(name, null);
        uid.setPath("/");
        uid.setMaxAge(0);
        response.addCookie(uid);
    }

    /**
     * 获取cookie值
     */
    public static String getValue(HttpServletRequest request, String cookieName) {
        Cookie cookies[] = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(cookieName)) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    /**
     * 获取用户ID
     */
    public static String getUserId(HttpServletRequest request) {
        return getValue(request, USER_ID_KEY);
    }

    /**
     * 获取用户名称
     */
    public static String getUserName(HttpServletRequest request) {
        return getValue(request, USER_NAME_KEY);
    }

    /**
     * 获取用户登录token
     */
    public static String getLoginToken(HttpServletRequest request) {
        return getValue(request, TOKEN_KEY);
    }

    /**
     * 当前登录用户是否是管理员
     *
     * @param request
     * @return
     */
    public static boolean isAdmin(HttpServletRequest request) {
        return ADMIN_USER_ID.equals(getUserId(request));
    }

    /**
     * 获取项目ID
     */
    public static String getProjectId(HttpServletRequest request) {
        return getValue(request, PROJECT_KEY);
    }

}
